//
//  CountDownTime.swift
//  jiaoyi
//
//  Created by wjk on 2018/11/9.
//  Copyright © 2018 wjk. All rights reserved.
//

import UIKit

class CountDownTime: UIView {

    @IBOutlet weak var labelCount: UILabel!
    @IBOutlet weak var labelTitle: UILabel!
    
    var count:Int = 30
    
    var title:String! {
        didSet {
            labelTitle.text = title
        }
    }
    
    var timer2:DispatchSourceTimer?
    var bl:okBlock?
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    public static func CountDownView() -> CountDownTime {
        let view = Bundle.main.loadNibNamed("CountDownTime", owner: nil, options: nil)?.first as! CountDownTime
        return view
    }
    
    
    public func DispatchTimer2(timeInterval: Double, handler:@escaping (DispatchSourceTimer?)->())
    {
        timer2?.cancel()
        timer2 = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        timer2?.schedule(deadline: .now(), repeating: timeInterval)
        timer2?.setEventHandler {
            DispatchQueue.main.async {
                handler(self.timer2)
            }
        }
        timer2?.resume()
    }
    
    func updateCount() -> Void {
        self.DispatchTimer2(timeInterval: 1) { (tim) in
            self.count = self.count - 1
            if self.count < 0 {
                self.bl?(["":""])
                tim?.cancel()
            }else {
                self.labelCount.text = "\(self.count)"
            }
        }
    }
    
    func clearTimer() -> Void {
        self.count = 0;
        timer2?.cancel()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
//        draw.center = self.center
//        self.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
//        draw.backgroundColor = .clear
//        self.addSubview(draw)
    }
    
    
   
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        self.removeFromSuperview()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
//        fatalError("init(coder:) has not been implemented")
    }
}
